/**
 * 原生路由的实现
 */
const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
//路径渲染
function render(page){
	return new Promise((resolve, reject) =>{
		let pageUrl = `../page/${page}`; // 相对的要访问的路由文件路径
		//binary 二进制的，data是以二进制Buffer格式保存的，可以说data就是想要的 Blob binary data
		fs.readFile(pageUrl, 'binary', (err, data) => { 
			console.log('天宇无敌');
			if(err){
				reject(err);
			}else{
				resolve(data);
			}
		})
	})
}
//处理路由跳转
async function route(url){
	let page = 'error.html';
	switch (url) {
		case '/':
			page = 'index.html';
			break;
        case '/index':
            page ='index.html';
            break;
        case '/todo':
            page = 'todo.html';
            break;
        case '/404':
            page = 'error.html';
            break;
        default:
            page = 'error.html';
            break; 
	}
	let html = await render(page);
	return html;
}

app.use(async (ctx) => {
	let url = ctx.request.url;
	let html = await route(url);
	ctx.body = html;
})

app.listen(3000, () =>{
	console.log('[demo] server is starting at port 3000');
})